#!/bin/bash

# 定义日志文件
LOG_FILE="$HOME/install_protoc.log"

echo "This script will install protobuf v3.25.4 and its dependencies on your system. The log of this installation process will be saved in $LOG_FILE"

# 定义工作目录
WORK_DIR="$HOME/protoc_installation"

# 保存当前工作目录
pushd . >/dev/null

# 创建工作目录
mkdir -p "$WORK_DIR" && cd "$WORK_DIR" || exit

# 安装 protoc 及其依赖 abseil

# 安装编译依赖
sudo yum install -y g++ bazel

# 安装 abseil
cd "$WORK_DIR" || exit
wget -c https://github.com/abseil/abseil-cpp/archive/refs/tags/20240116.2.tar.gz
tar -zxf 20240116.2.tar.gz
rm -rf 20240116.2.tar.gz
mv ./abseil-cpp-20240116.2/ ./abseil-cpp
cd abseil-cpp/ || exit
cmake ./ -DCMAKE_CXX_STANDARD=20
make -j "$(nproc)" && sudo make install

# 下载并编译 protobuf
cd "$WORK_DIR" || exit
wget -c https://github.com/protocolbuffers/protobuf/archive/refs/tags/v3.25.4.tar.gz
tar -zxf v3.25.4.tar.gz
cd protobuf-3.25.4 || exit

# 将 abseil 添加到 protobuf 的第三方依赖中
cp -r "$WORK_DIR/abseil-cpp" ./third_party
cmake ./ -DCMAKE_BUILD_TYPE=RELEASE -Dprotobuf_BUILD_TESTS=off -DCMAKE_CXX_STANDARD=20
sudo make install -j 32

# 确认 protoc 安装正确并设置环境变量
PROTOC_VERSION="3.25.4"
if [ -x "/usr/local/bin/protoc" ]; then
    # 设置环境变量
    export PATH="/usr/local/bin:$PATH"

    # 验证 protoc 版本
    if [ "$(protoc --version | grep -c "libprotoc${PROTOC_VERSION}")" -eq 1 ]; then
        echo "protoc install finished, current version is: $(protoc --version)" | tee -a "$LOG_FILE"

        # 使用 Maven 安装 protoc
        mvn install:install-file \
            -DgroupId=com.google.protobuf \
            -DartifactId=protoc \
            -Dversion="${PROTOC_VERSION}" \
            -Dclassifier=linux-riscv64 \
            -Dpackaging=exe \
            -Dfile=/usr/local/bin/protoc
    else
        echo "protoc install failed, version is not ${PROTOC_VERSION}" | tee -a "$LOG_FILE"
    fi
else
    echo "protoc install failed, /usr/local/bin/protoc not found" | tee -a "$LOG_FILE"
fi

# 清理源码目录
rm -rf "$WORK_DIR"

# 输出安装完成信息
echo "this script is finished" | tee -a "$LOG_FILE"

# 恢复之前的工作目录
popd >/dev/null || exit
